// pages/personaldata/personaldata.js
import * as api from '../../utils/api.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    index: 0,
    userinfo: {},
    loginType:''
  },
  onChooseAvatar(eh) {
    const { avatarUrl } = eh.detail 
    const that = this
    this.setData({
      avatarUrl,
    })
    api.upload(avatarUrl)
      .then(res => {
        that.setData({
          'userinfo.avatar': res.data.url
        })
      })
      .catch(err => console.log(err))
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
  },

  inputEvent(e) {
    const name = e.currentTarget.dataset.name
    const value = e.detail.value.trim()
    let userinfo = this.data.userinfo
    userinfo[name] = value
    this.setData({
      userinfo
    })
  },

  saveUserInfo() {
    const userinfo = this.data.userinfo
    const nickname = userinfo.nickname
    const mobile = userinfo.mobile
    const address = userinfo.address
    const avatar = userinfo.avatar
    const password = userinfo.password ? userinfo.password : ''
    api.userProfile(nickname,mobile,address,avatar,password)
      .then(res => {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })
        wx.setStorageSync('userinfo', userinfo)
        setTimeout(function(){
          wx.navigateBack({
            delta: 1
          });
        },1500)
      }).catch(err => {
        console.log(err)
        wx.showToast({
          title: err.msg,
          icon: 'error'
        })
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const that = this
    that.setData({
      loginType:wx.getStorageSync('loginType')
    })
    const userinfo = wx.getStorageSync('userinfo')
    if(userinfo) {
      that.setData({
        userinfo,
      })
    } else {
      wx.login().then(res => {
          const code = res.code
          api.userLogin(code)
            .then(res => {
              console.log(res)
              let userinfo = res.data.userinfo;
              userinfo.avatar = userinfo.avatar.startsWith('/') ? that.data.domain + userinfo.avatar : userinfo.avatar
              wx.setStorageSync('token', userinfo.token)
              wx.setStorageSync('userinfo', userinfo)
              wx.setStorageSync('loginType', 'user')
              that.setData({
                userinfo,
              })
            }).catch(err => {
              wx.showToast({
                title: err.msg,
                icon: 'error'
              })
            })
        })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})